import os
import json
import base64
import requests
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.auth.credentials import AccessKeyCredential
import logging

logger = logging.getLogger(__name__)


class AliyunSpeechRecognizerFixed:
    def __init__(self, access_key_id, access_key_secret, app_key, region='cn-shanghai'):
        self.access_key_id = access_key_id
        self.access_key_secret = access_key_secret
        self.app_key = app_key
        self.region = region
        self.endpoint = f'https://nls-gateway.{region}.aliyuncs.com'

    def recognize_file(self, audio_file_path, sample_rate=16000, method='rest'):
        """
        语音识别主方法，支持多种调用方式
        """
        if method == 'rest':
            return self._recognize_rest(audio_file_path, sample_rate)
        elif method == 'sdk_simple':
            return self._recognize_sdk_simple(audio_file_path, sample_rate)
        else:
            return self._recognize_direct(audio_file_path, sample_rate)

    def _recognize_rest(self, audio_file_path, sample_rate):
        """使用REST API"""
        try:
            with open(audio_file_path, 'rb') as f:
                audio_data = f.read()

            audio_base64 = base64.b64encode(audio_data).decode('utf-8')

            payload = {
                'Task': {
                    'appkey': self.app_key,
                    'format': 'pcm',
                    'sample_rate': sample_rate,
                    'enable_inverse_text_normalization': True
                },
                'Audio': audio_base64
            }

            headers = {
                'Content-Type': 'application/json'
            }

            response = requests.post(
                f'{self.endpoint}/recognize',
                headers=headers,
                json=payload,
                timeout=30
            )

            if response.status_code == 200:
                return response.json()
            else:
                logger.error(f"HTTP {response.status_code}: {response.text}")
                return None

        except Exception as e:
            logger.error(f"REST调用异常: {e}")
            return None

    def _recognize_sdk_simple(self, audio_file_path, sample_rate):
        """使用简化版SDK调用"""
        try:
            credentials = AccessKeyCredential(self.access_key_id, self.access_key_secret)
            client = AcsClient(region_id=self.region, credential=credentials)

            from aliyunsdkcore.request import CommonRequest
            request = CommonRequest()
            request.set_domain(f'nls-gateway.{self.region}.aliyuncs.com')
            request.set_version('2018-05-18')
            request.set_action_name('RecognizeSpeech')
            request.set_protocol_type('https')
            request.set_method('POST')

            # 读取音频文件
            with open(audio_file_path, 'rb') as f:
                audio_data = f.read()

            audio_base64 = base64.b64encode(audio_data).decode('utf-8')

            # 构建请求体
            request_body = {
                'Task': json.dumps({
                    'appkey': self.app_key,
                    'format': 'pcm',
                    'sample_rate': sample_rate
                }),
                'Audio': audio_base64
            }

            request.set_content(json.dumps(request_body).encode('utf-8'))
            request.set_content_type('application/json')

            response = client.do_action_with_exception(request)
            return json.loads(response.decode('utf-8'))

        except Exception as e:
            logger.error(f"SDK调用异常: {e}")
            return None


# 使用示例
def main():
    # 配置信息
    config = {
        'access_key_id': "LTAI5tG4A6DzaQ8RuW7aSq59",
        'access_key_secret': "aBK7ijCmwSspSqhd9JuR4rl2oeE45x",
        'app_key': "ey0QwYdnT04iBSgz",
        'region': 'cn-shanghai'
    }

    # 初始化识别器
    recognizer = AliyunSpeechRecognizerFixed(**config)

    # 识别音频文件（优先使用REST API）
    result = recognizer.recognize_file(
        '/home/suke/tangqi/ai_arm_controller/audio_file/1.mp3',
        method='rest'  # 使用REST API避免header问题
    )

    if result and result.get('Status') == 20000000:
        print("识别结果:", result['Result']['Text'])
    else:
        print("识别失败")


if __name__ == "__main__":
    main()